package com.byron.media.server.client;

import com.byron.media.server.enums.MediaType;
import com.byron.media.server.model.DataFactory;
import com.byron.media.server.model.MediaData;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import org.apache.log4j.Logger;

import java.util.concurrent.TimeUnit;

@ChannelHandler.Sharable
public class MediaClientHeartBeat extends IdleStateHandler {

    private static Logger logger = Logger.getLogger(MediaClientHeartBeat.class);

    private MediaClientConfig config;

    public MediaClientHeartBeat(MediaClientConfig config, int heartTimeout) {
//        super(0, 0, config.getAllIdleTimeSeconds());
        super(true, 0, heartTimeout, 0, TimeUnit.SECONDS);
        this.config = config;
    }

    @Override
    protected void channelIdle(ChannelHandlerContext ctx, IdleStateEvent evt) throws Exception {
        if(evt.state().equals(IdleState.READER_IDLE)){
            logger.info("流媒体读超时");
            return;
        }
        if(evt.state().equals(IdleState.WRITER_IDLE)){
//            logger.info("流媒体写超时");
            MediaData heartData = DataFactory.getInstance().createData(0);
            byte type = 0;
            type = MediaType.putHeart(type);
            type = MediaType.putStart(type);
            type = MediaType.putEnd(type);
            heartData.setType(type);
            heartData.setServerId(config.getServerId());
            ctx.writeAndFlush(heartData);
            return;
        }
        if(evt.state().equals(IdleState.ALL_IDLE)){
            logger.info("流媒体读写超时");
            return;
        }
    }

}
